<?php
/**
 * Medical Study Search Add Partner Popup
 *
 * This popup allows the user to add existing partners
 * to the current ms
 *
 */

use Nawa\MedicalCenter;
use Nawa\Customer;
use Fox\Dao\SqlFragment;
use Nawa\MedicalStudy\Role;
use Fox\Html\Input;
use Fox\Html\TextArea;
use Doctrine\DBAL\Connection;
use Fox\Generator;
use Fox\Html\DropList;
use Fox\Html\Screen;
use Nawa\MedicalStudy;

$xview = Xview::instance();
$id = Xview::instance()->val('mcid');
$msid = Xview::instance()->val('msid');
$excluded = array();
$shlpName = 'MedicalCenters';
$searchHelp = new Fox\Html\SearchHelp($shlpName);
$searchHelp->width(500);
$searchHelp->setMultiple(new Fox\Html\Button('select',
	Generator::reloadFromSelectedLines("#b_GR$shlpName",
							'MC_gMedicalCentersPartners',
							Generator::url('medicalstudies','medicalcenters',null,array('msid' => $msid)),
							"hide(\'sh:$shlpName\')",
							"InputSerialize(\'BC_bMedicalCentersPartners\')"
)));
								
$searchHelp->switchToObjectMode();
$ilink = $xview->currentURL();
$searchHelp->getSelBlock()->add(new TextArea('excluded'))->excluded()->hidden();
$searchHelp->getSelBlock()->add(new Fox\Html\Input('mcid',false,$id))
	->excluded()
	->hidden();
// Load already selected Product
$bPartner = Xview::instance()->component('medicalstudies', 'medicalcenters',array('xvtrs' => false));
$data = $bPartner->item('gMedicalCentersPartners')->get(true);
if(is_array($data['gMedicalCentersPartners']))
{
	foreach($data['gMedicalCentersPartners'] as $line)
	{
		if(isset($line['mcid']))
		$Ids[] = $line['mcid'];
	}

	if(!empty($id)) {
		$Ids[] = $id;
	}
	
	if(isset($Ids))
	{
		$excluded = new \Fox\Dao\SqlFragment('mcid NOT IN (?) ',array($Ids),array(Connection::PARAM_STR_ARRAY));
		$searchHelp->getSelBlock()->item('excluded')->default = addslashes(json_encode($Ids));
	}
}
else
{
	$values = Xview::instance()->val('excluded');
	if(!empty($values))
	{
		$Ids = json_decode(stripcslashes($values),true);
		$excluded = new \Fox\Dao\SqlFragment('mcid NOT IN (?) ',array($Ids),array(Connection::PARAM_STR_ARRAY));
	}
}
// Filter By Customer Type
$searchHelp->getSelBlock()
	->item('mc_reference_intern')
	->id('reference');

if(isset($_POST['dbcnt']) && 1 == 1)
{
	$inputs = $searchHelp->screen()->get();
	$fragments[] = $searchHelp->screen()->fragments();
	$finder = new MedicalCenter();
	if(isset($excluded))
	$fragments[] = $excluded;
	$res = $finder->find(Fox\Dao\SqlFragment::combine($fragments),array('name1' => false),null,$inputs['dbcnt']);
	$searchHelp->grid()->fieldcat()->setGenerators(array('mc_reference_intern' => Generator::useAttribute('reference'),));
	$searchHelp->grid()->getFieldcat()->field('mcid')->hidden(true);
	$searchHelp->grid()->setDatas($res);
	echo $searchHelp->grid()->Display();
}
else {
	echo $searchHelp->display();
}